//
//  AddressBookViewController.m
//  Logistics
//
//  Created by hy002 on 2018/1/17.
//  Copyright © 2018年 HUYU. All rights reserved.
//

#import "AddressBookViewController.h"
#import "PhoneNumModel.h"
#import "FocusonModel.h"

static NSString *cellPath = @"AddressBookCell";
@interface AddressBookViewController ()<UITableViewDelegate,UITableViewDataSource>
{
    UIView *topView;
    UIView *lineView;
    UIView *showView;
}
@property (nonatomic, strong)UITableView *tableview;
@property (nonatomic, assign)NSInteger closeType;
@property (nonatomic, strong)NSArray *commonlyAry;
@property (nonatomic, strong)NSArray *focusonAry;
@property (nonatomic, strong)NSArray *historyAry;
@property (nonatomic, strong)NSString *Phonename;
@property (nonatomic, strong)NSString *PhoneNum;
@property (nonatomic, strong)NSString *imgUrl;

@end

@implementation AddressBookViewController
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    NSNotificationCenter * center = [NSNotificationCenter defaultCenter];
    [center addObserver:self selector:@selector(callPhonesNotifice:) name:@"callPhones" object:nil];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"callPhones" object:nil];
}


- (void)callPhonesNotifice:(NSNotification *)center
{
    NSString *timeStr = [center object];
    Student *stu = [Student studentWith:_imgUrl name:_Phonename Phone:_PhoneNum Times:timeStr];
    BOOL isInsert = [StudentFMDNManager addStudent:stu];
    
    if (isInsert) {
        NSLog(@"插入成功");
    } else {
        NSLog(@"插入失败");
    }
    _historyAry = [StudentFMDNManager queryStudent:nil];
    dispatch_async(dispatch_get_main_queue(), ^{
        [_tableview reloadData];
    });
}
- (void)viewDidLoad {
    [super viewDidLoad];
    _closeType = 0;
    _historyAry = [StudentFMDNManager queryStudent:nil];
    [self creatUI];
    [self requestCommonly];
    [self requestFocusonList];
}

- (void)creatUI
{
    self.navigationItem.title = @"通讯录";
    self.navigationController.navigationBar.translucent = NO;
    self.view.backgroundColor = BacksColor;
    [self creatScreeView];
    self.tableview = [[UITableView alloc] initWithFrame:CGRectMake(0, 45*displaywidth, SCREEN_WIDTH, SCREEN_HEIGHT-STA_NAV_HEIGHT-45*displaywidth-SCREER_HeiX) style:UITableViewStylePlain];
    _tableview.backgroundColor = BacksColor;
    _tableview.delegate = self;
    _tableview.dataSource = self;
    _tableview.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:_tableview];
    showView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    showView.backgroundColor = RGBA(0, 0, 0, 0.6);
    showView.hidden = YES;
    [sharedDelegate.window addSubview:showView];
    
}

- (void)creatScreeView
{
    NSArray *typeAry = @[@"常用电话",@"关注的人",@"通话记录"];
    UIView *topView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 45*displaywidth)];
    topView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:topView];
    CGFloat W = SCREEN_WIDTH/typeAry.count;
    for (int i = 0; i < typeAry.count; i++)
    {
        UIButton *btn = [ZCControl createButtonWithFrame:CGRectMake(W*i, 0, W, 45*displaywidth) ImageName:nil Target:self Action:@selector(closeRoursAction:) Title:typeAry[i] Font:15.0];
        [btn setTitleColor:BlaTitColor forState:UIControlStateNormal];
        if (i == 0)
        {
            [btn setTitleColor:ThemeColor forState:UIControlStateNormal];
        }
        btn.backgroundColor = [UIColor clearColor];
        btn.tag = 100+i;
        [topView addSubview:btn];
    }
    lineView = [[UIView alloc] initWithFrame:CGRectMake(0, 43.5*displaywidth, W, 1.5*displaywidth)];
    lineView.backgroundColor = ThemeColor;
    [topView addSubview:lineView];
}

- (void)closeRoursAction:(UIButton *)btn
{
    if (_closeType != (btn.tag-100))
    {
        _closeType = btn.tag-100;
        for (id v in topView.subviews)
        {
            if ([v isKindOfClass:[UIButton class]])
            {
                UIButton *button = (UIButton *)v;
                [button setTitleColor:BlaTitColor forState:UIControlStateNormal];
            }
        }
        [btn setTitleColor:ThemeColor forState:UIControlStateNormal];
        lineView.frame = CGRectMake(SCREEN_WIDTH/3*_closeType, 43.5*displaywidth, SCREEN_WIDTH/3, 1.5*displaywidth);
        [_tableview reloadData];
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (_closeType == 0)
    {
        return _commonlyAry.count;
    }
    else if (_closeType == 1)
    {
        return _focusonAry.count;
    }
    return _historyAry.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    if (!cell)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellPath];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.backgroundColor = [UIColor whiteColor];
    for (id v in cell.contentView.subviews)
    {
        [v removeFromSuperview];
    }
    UIView *lineAv = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 1*displaywidth)];
    lineAv.backgroundColor = BacksColor;
    [cell.contentView addSubview:lineAv];
    if (_closeType != 2)
    {
        NSString *imgStr = @"";
        NSString *nameStr = @"";
        NSString *phoneStr = @"";
        if (_closeType == 0)
        {
            if (_commonlyAry.count == 0)
            {
                return cell;
            }
            PhoneNumModel *model = _commonlyAry[indexPath.row];
            imgStr = model.logo;
            nameStr = model.nameShort;
            phoneStr = model.fixPhone;
        }
        else
        {
            if (_focusonAry.count == 0)
            {
                return cell;
            }
            FocusonModel *faModel = _focusonAry[indexPath.row];
            if ([faModel.type integerValue] == 3)
            {
                imgStr = faModel.user.headImg;
                nameStr = faModel.user.username;
                phoneStr = faModel.user.phone;
            }
            else if ([faModel.type integerValue] == 2)
            {
                imgStr = faModel.truckheadImg;
                nameStr = faModel.trucklinkman;
                phoneStr = faModel.truckphone;
            }
            else
            {
                imgStr = faModel.company.logo;
                nameStr = faModel.company.nameShort;
                phoneStr = faModel.company.fixPhone;
            }
            
        }
        UIImageView *imgView = [ZCControl createImageViewWithFrame:CGRectMake(15*displaywidth, 10*displaywidth, 40*displaywidth, 40*displaywidth) ImageName:@""];
        if (![imgStr isEqualToString:@""])
        {
            [imgView sd_setImageWithURL:URL(imgStr)];
        }
        imgView.contentMode = UIViewContentModeScaleAspectFill;
        imgView.layer.cornerRadius = 20*displaywidth;
        imgView.layer.masksToBounds = YES;
        [cell.contentView addSubview:imgView];
        UILabel *nameLab = [ZCControl createLabelWithFrame:CGRectMake(65*displaywidth, 5*displaywidth, SCREEN_WIDTH-250*displaywidth, 50*displaywidth) Font:14.0 Text:nameStr Color:BlaTitColor];
        [cell.contentView addSubview:nameLab];
        
        UIButton *phoneBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        phoneBtn.backgroundColor = RGB(255, 247, 237);
        phoneBtn.frame = CGRectMake(SCREEN_WIDTH-180*displaywidth, 17.5*displayheight, 160*displaywidth, 25*displayheight);
        [phoneBtn setImage:[UIImage imageNamed:@"tel2"] forState:UIControlStateNormal];
        phoneBtn.titleLabel.font = [UIFont systemFontOfSize:15];
        [phoneBtn setTitleColor:RGB(187, 176, 170) forState:UIControlStateNormal];
        [phoneBtn setTitle:phoneStr forState:UIControlStateNormal];
        [phoneBtn addTarget:self action:@selector(phoneBtnAction:) forControlEvents:UIControlEventTouchUpInside];
        CGSize imgSize = phoneBtn.currentImage.size;
        CGSize titleSize = [phoneBtn.titleLabel.text sizeWithAttributes:@{NSFontAttributeName:phoneBtn.titleLabel.font}];
        UIEdgeInsets   titleEdgeInsets = UIEdgeInsetsMake(0, -imgSize.width-5, 0, imgSize.width+10);
        UIEdgeInsets imgEdgeInsets = UIEdgeInsetsMake(0, 5+titleSize.width, 0, -titleSize.width+5);
        phoneBtn.titleEdgeInsets = titleEdgeInsets;
        phoneBtn.imageEdgeInsets = imgEdgeInsets;
        phoneBtn.layer.cornerRadius = 12.5*displayheight;
        phoneBtn.layer.borderWidth = 1;
        phoneBtn.layer.borderColor = RGBA(255, 153, 20, 0.34).CGColor;
        phoneBtn.layer.masksToBounds = YES;
        phoneBtn.tag = 1000+indexPath.row;
        phoneBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
        phoneBtn.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
        phoneBtn.frame = CGRectMake(SCREEN_WIDTH- (imgSize.width+titleSize.width+20*displaywidth)-20*displaywidth, 17.5*displaywidth, imgSize.width+titleSize.width+20*displaywidth, 25*displaywidth);
        [cell.contentView addSubview:phoneBtn];
        
    }
    else
    {
        if (_historyAry.count != 0)
        {
            NSInteger num = _historyAry.count;
            Student *stu = _historyAry[num-1-indexPath.row];
            UIImageView *imgView = [ZCControl createImageViewWithFrame:CGRectMake(15*displaywidth, 10*displaywidth, 40*displaywidth, 40*displaywidth) ImageName:@""];
            if (![stu.imgURL isEqualToString:@""])
            {
                [imgView sd_setImageWithURL:URL(stu.imgURL)];
            }
            else
            {
                imgView.image = IMAGE(@"logo3x60");
            }
            imgView.contentMode = UIViewContentModeScaleAspectFill;
            imgView.layer.cornerRadius = 20*displaywidth;
            imgView.layer.masksToBounds = YES;
            [cell.contentView addSubview:imgView];
            UILabel *nameLab = [ZCControl createLabelWithFrame:CGRectMake(65*displaywidth, 5*displaywidth, SCREEN_WIDTH-250*displaywidth, 50*displaywidth) Font:14.0 Text:[stu.name stringByReplacingOccurrencesOfString:@"null" withString:@""] Color:BlaTitColor];
            [cell.contentView addSubview:nameLab];
            UILabel *phoneLab = [ZCControl createLabelWithFrame:CGRectMake(SCREEN_WIDTH/2, 10*displaywidth, SCREEN_WIDTH/2-10*displaywidth, 20*displaywidth) Font:12.0 Text:stu.Phone Color:RGB(153, 153, 153)];
            phoneLab.textAlignment = NSTextAlignmentRight;
            [cell.contentView addSubview:phoneLab];
            UILabel *timeLab = [ZCControl createLabelWithFrame:CGRectMake(SCREEN_WIDTH/2, 30*displaywidth, SCREEN_WIDTH/2-10*displaywidth, 20*displaywidth) Font:12.0 Text:stu.times Color:RGB(153, 153, 153)];
            timeLab.textAlignment = NSTextAlignmentRight;
            [cell.contentView addSubview:timeLab];
        }
    }
    return cell;
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (_closeType == 2)
    {
        NSInteger num = _historyAry.count;
        Student *stu = _historyAry[num-1-indexPath.row];
        _imgUrl = stu.imgURL;
        _Phonename = stu.name;
        _PhoneNum = stu.Phone;
        [[UIApplication sharedApplication]openURL:[NSURL URLWithString:[NSString stringWithFormat:@"tel://%@",stu.Phone]]];

    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 60*displaywidth;
}

- (void)phoneBtnAction:(UIButton *)btn
{
    NSInteger index = btn.tag - 1000;
    NSString *imgStr = @"";
    NSString *nameStr = @"";
    NSString *phoneStr = @"";
    NSString *fixPhone = @"";
    if (_closeType == 0)
    {
        PhoneNumModel *model = _commonlyAry[index];
        imgStr = model.logo;
        nameStr = [NSString stringWithFormat:@"%@-%@",model.nameShort,model.linkman];
        phoneStr = model.phone;
        fixPhone = model.fixPhone;
    }
    else
    {
        FocusonModel *faModel = _focusonAry[index];
        if ([faModel.type integerValue] == 3)
        {
            imgStr = faModel.user.headImg;
            nameStr = faModel.user.username;
            phoneStr = faModel.user.phone;
        }
        else if ([faModel.type integerValue] == 2)
        {
            imgStr = faModel.truckheadImg;
            nameStr = faModel.trucklinkman;
            phoneStr = faModel.truckphone;
        }
        else
        {
            imgStr = faModel.company.logo;
            nameStr = faModel.company.nameShort;
            phoneStr = faModel.company.fixPhone;
        }
    }
    [self creatShowView:imgStr Name:nameStr Phone:phoneStr FixPhone:fixPhone];
}

- (void)creatShowView:(NSString *)imgStr Name:(NSString *)name Phone:(NSString *)phone FixPhone:(NSString *)fixPhone
{
    for (id v in showView.subviews)
    {
        [v removeFromSuperview];
    }
    showView.hidden = NO;
    UIView *whiteView = [[UIView alloc] initWithFrame:CGRectMake(40*displaywidth, SCREEN_HEIGHT/2-100*displaywidth, SCREEN_WIDTH-80*displaywidth, 185*displaywidth)];
    whiteView.backgroundColor = [UIColor whiteColor];
    whiteView.layer.cornerRadius = 10;
    whiteView.layer.masksToBounds = YES;
    [showView addSubview:whiteView];
    UIView *topView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH-80*displaywidth, 85*displaywidth)];
    topView.backgroundColor = ThemeColor;
    [whiteView addSubview:topView];
    UIButton *closeBtn = [ZCControl createButtonWithFrame:CGRectMake(SCREEN_WIDTH-120*displaywidth, 10*displaywidth, 25*displaywidth, 25*displaywidth) ImageName:@"closeicon" Target:self Action:@selector(closeViewAction) Title:nil Font:12.0];
    [topView addSubview:closeBtn];
    UILabel *tostLab = [ZCControl createLabelWithFrame:CGRectMake(0, 45*displaywidth, SCREEN_WIDTH-80*displaywidth, 30*displaywidth) Font:14.0 Text:@"联系时，请说明信息来自专线网" Color:RGB(218,222,232)];
    tostLab.textAlignment = NSTextAlignmentCenter;
    [topView addSubview:tostLab];
    CGFloat H = 85*displaywidth;
    if (phone.length > 0)
    {
        UIButton *btn = [ZCControl createButtonWithFrame:CGRectMake(0, H, SCREEN_WIDTH-80*displaywidth, 49*displaywidth) ImageName:nil Target:self Action:@selector(callphone:) Title:name Font:15.0];
        objc_setAssociatedObject(btn, "firstObject", name, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
        objc_setAssociatedObject(btn, "secondObject", phone, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
        objc_setAssociatedObject(btn, "thirdObject", imgStr, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
        [btn setTitleColor:ThemeColor forState:UIControlStateNormal];
        [whiteView addSubview:btn];
        H = 135*displaywidth;
    }
    if (fixPhone.length > 0)
    {
        if (H == 135*displaywidth)
        {
            UIView *lineview = [[UIView alloc] initWithFrame:CGRectMake(10*displaywidth, H-1*displaywidth, SCREEN_WIDTH-100*displaywidth, 1*displaywidth)];
            lineview.backgroundColor = RGB(218, 222, 232);
            [whiteView addSubview:lineview];
            
        }
        UIButton *btn2 = [ZCControl createButtonWithFrame:CGRectMake(0, H, SCREEN_WIDTH-80*displaywidth, 50*displaywidth) ImageName:nil Target:self Action:@selector(callphone:) Title:@"售后服务" Font:15.0];
        objc_setAssociatedObject(btn2, "firstObject", name, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
        objc_setAssociatedObject(btn2, "secondObject", fixPhone, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
        objc_setAssociatedObject(btn2, "thirdObject", imgStr, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
        [btn2 setTitleColor:ThemeColor forState:UIControlStateNormal];
        [whiteView addSubview:btn2];
        H+=50*displaywidth;
    }
    whiteView.frame = CGRectMake(40*displaywidth, SCREEN_HEIGHT/2-100*displaywidth, SCREEN_WIDTH-80*displaywidth, H);
    
}

- (void)closeViewAction
{
    showView.hidden = YES;
    
}

- (void)callphone:(UIButton *)btn
{
    showView.hidden = YES;
    _Phonename = objc_getAssociatedObject(btn, "firstObject");
    _imgUrl = objc_getAssociatedObject(btn, "thirdObject");
    NSString *phone = objc_getAssociatedObject(btn, "secondObject");
    _PhoneNum = phone;
    [[UIApplication sharedApplication]openURL:[NSURL URLWithString:[NSString stringWithFormat:@"tel://%@",phone]]];
    
}

//常用电话
- (void)requestCommonly
{
    WEAKSELF;
    NSDictionary *dic = @{@"size":@"999"};
    [HYBaseHandler requestWithTheFormUrl:SERVER_commonly Parmers:dic Success:^(id obj) {
        if ([obj server_Getcodecheck])
        {
            _commonlyAry = [PhoneNumModel mj_objectArrayWithKeyValuesArray:obj[@"data"][@"content"]];
            dispatch_async(dispatch_get_main_queue(), ^{
                [weakSelf.tableview reloadData];
            });
        }
        else
        {
            [LTools showMBProgressWithText:obj[@"msg"] addToView:weakSelf.view];
        }
    } failed:^(NSError *error) {
        
    }];
}

//关注的人
- (void)requestFocusonList
{
    WEAKSELF;
    NSDictionary *dic = @{@"size":@"999"};
    [HYBaseHandler requestWithTheFormUrl:SERVER_FocusOn Parmers:dic Success:^(id obj) {
        if ([obj server_Getcodecheck])
        {
            _focusonAry = [FocusonModel mj_objectArrayWithKeyValuesArray:obj[@"data"][@"content"]];
            dispatch_async(dispatch_get_main_queue(), ^{
                [weakSelf.tableview reloadData];
            });
        }
        else
        {
            [LTools showMBProgressWithText:obj[@"msg"] addToView:weakSelf.view];
        }
    } failed:^(NSError *error) {
        
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
